<!-- 策略管理 -->
<script setup xmlns="http://www.w3.org/1999/html">
import {reactive, ref} from "vue";
import {CirclePlus} from "@element-plus/icons-vue";
import SelectConfig from '@/components/SelectConfig/index.vue'
import {AddStrategy, DebugStrategy} from "@/api/strategy";
import {ElMessage} from "element-plus";
import {getVtSymbol} from "@/api/common";

const activeNames = ref('')

const ruleForm = ref({
 strategy_name: '策略1', // 策略名称
 symbol: 'rb',
 internal: "1m",
 internal_count: 15,
 maizhang: [], // 买涨
 maizhangpingcang: [], // 买涨平仓
 maidie: [], // 买跌
 maidiepingcang: [], // 买跌平仓，
 // tSellMa: [{tSellMa: []}], // 5-0策略，
 price_set: {
  buy_up: '',
  buy_up_close: '',
  buy_down: '',
  buy_down_close: '',
  fix_size: '',
  money: 100000
 },
})

const props = reactive({ multiple: true })

const options = ref([])

const toAddStrategySetting = (name) => {
 ruleForm.value[name].push([])
}

// 判断节点是否为第三级
const isThirdLevel = (node) => {
 return node.level === 3;
}

const onValue = ({index, value}, data, node) => {
 data.value[index] = value
 console.log(data, options.value)
}

// 删除
const handleDelete = () => {

}

// 保存交易执行价格
const loading = ref(false)
const handleAddPrice = async (type) => {
 let maizhang = formatArr(ruleForm.value.maizhang)
 let maizhangpingcang = formatArr(ruleForm.value.maizhangpingcang) // 买涨平仓
 let maidie = formatArr(ruleForm.value.maidie) // 买跌
 let maidiepingcang = formatArr(ruleForm.value.maidiepingcang) // 买跌平仓

 let price_set = {};

 for (let i in ruleForm.value.price_set) {
  price_set[i] = +ruleForm.value.price_set[i] || 0
 }

 loading.value = true
 const request = type === 0 ? AddStrategy : DebugStrategy

 Promise.try(() => {
  return request({
   ...ruleForm.value,
   maizhang,
   maidiepingcang,
   maidie,
   maizhangpingcang,
   price_set
  })
 }).then(res => {
  res && ElMessage.success(type === 0 ? '保存成功' : '调试成功')
 })

 loading.value = false
}

// 格式化
const formatArr = (oldArr) => {
 let list = []


 oldArr.forEach(item => {
  item.forEach(i => {
   list.push(i)
  })
 })

 return groupByCategory(list, 0)
}

// 根据字段划分小组
const groupByCategory = (arr, index) => {
 return arr.reduce((acc, item) => {
  const key = item[index];  // 根据指定的下标值进行分组
  if (!acc[key]) {
   acc[key] = [];  // 如果没有该值，创建一个新数组
  }
  console.log(item)
  acc[key].push({
   indicator: item[0],
   level: item.length,
   MACD: item[2] ? item[2].map(item => {
    return +item || 0
   }) : []
  });  // 将当前项推入对应的数组
  return acc;
 }, {});
}

// 获取vt编码
const getVtList = () => {
 Promise.try(() => {
  return getVtSymbol({
   symbol: 'rb'
  })
 }).then(res => {
  let arr = []

  res.data.forEach((item, index) => {
   arr.push({
    value: item.id,
    label: item.label
   })

   if (item.children) {
    arr[index].children = []
    item.children.forEach((item, i) => {
     arr[index].children.push({
      value: item.id,
      label: item.label
     })

     if (item.children) {
      arr[index].children[i].children = []
      item.children.forEach((item, b) => {
       arr[index].children[i].children.push({
        value: [item.id],
        uid: item.id,
        label: item.label
       })
      })
     }
    })
   }
  })

  options.value = arr
 })
}
getVtList()
</script>

<template>
 <div class="card" v-loading="loading">
  <div class="card_header flex">
   <h6 class="card_header_title">策略管理</h6>
  </div>

  <div class="card_main">
   <el-collapse accordion v-model="activeNames">

    <el-collapse-item>
     <template #title>
      <div class="collapse flex">
       <h6>买涨</h6>

       <CirclePlus @click.stop="toAddStrategySetting('maidiepingcang')" />
      </div>
     </template>

     <div class="box flex">
      <div class="price flex" v-for="(item, idx) of ruleForm.maidiepingcang" :key="idx">
       <div class="price_header flex">
        <p class="newSpan">{{ idx + 1 }}买: </p> <el-button type="danger" @click="handleDelete(idx,'bSellMa')">删除</el-button>
       </div>
       <el-cascader :props="props" class="newSelect" :lazy="true" ref="cascaderRef" :options="options" :show-all-levels="false" v-model="ruleForm.maidiepingcang[idx]">
        <template #default="{ node, data }">
         <!-- 判断是否为第三级节点 -->
         <div v-if="isThirdLevel(node)">
          <selectConfig :data="data" @onValue="value => onValue(value, data, node)" />
         </div>
         <span v-else>{{ data.label }}</span>
        </template>
       </el-cascader>
      </div>
     </div>
    </el-collapse-item>

    <el-collapse-item>
     <template #title>
      <div class="collapse flex">
       <h6>买涨平仓</h6>

       <CirclePlus @click.stop="toAddStrategySetting('maizhangpingcang')" />
      </div>
     </template>

     <div class="box flex">
      <div class="price flex" v-for="(item, idx) of ruleForm.maizhangpingcang" :key="idx">
       <div class="price_header flex">
        <p class="newSpan">{{ idx + 1 }}买: </p> <el-button type="danger" @click="handleDelete(idx,'bSellMa')">删除</el-button>
       </div>
       <el-cascader :props="props" class="newSelect" :lazy="true" ref="cascaderRef" :options="options" :show-all-levels="false" v-model="ruleForm.maizhangpingcang[idx]">
        <template #default="{ node, data }">
         <!-- 判断是否为第三级节点 -->
         <div v-if="isThirdLevel(node)">
          <selectConfig :data="data" @onValue="value => onValue(value, data, node)" />
         </div>
         <span v-else>{{ data.label }}</span>
        </template>
       </el-cascader>
      </div>
     </div>
    </el-collapse-item>

    <el-collapse-item>
     <template #title>
      <div class="collapse flex">
       <h6>买跌</h6>

       <CirclePlus @click.stop="toAddStrategySetting('maidie')" />
      </div>
     </template>

     <div class="box flex">
      <div class="price flex" v-for="(item, idx) of ruleForm.maidie" :key="idx">
       <div class="price_header flex">
        <p class="newSpan">{{ idx + 1 }}买: </p> <el-button type="danger" @click="handleDelete(idx,'bSellMa')">删除</el-button>
       </div>
       <el-cascader :props="props" class="newSelect" :lazy="true" ref="cascaderRef" :options="options" :show-all-levels="false" v-model="ruleForm.maidie[idx]">
        <template #default="{ node, data }">
         <!-- 判断是否为第三级节点 -->
         <div v-if="isThirdLevel(node)">
          <selectConfig :data="data" @onValue="value => onValue(value, data, node)" />
         </div>
         <span v-else>{{ data.label }}</span>
        </template>
       </el-cascader>
      </div>
     </div>
    </el-collapse-item>

    <el-collapse-item>
     <template #title>
      <div class="collapse flex">
       <h6>买跌平仓</h6>

       <CirclePlus @click.stop="toAddStrategySetting('maidiepingcang')" />
      </div>
     </template>

     <div class="box flex">
      <div class="price flex" v-for="(item, idx) of ruleForm.maidiepingcang" :key="idx">
       <div class="price_header flex">
        <p class="newSpan">{{ idx + 1 }}买: </p> <el-button type="danger" @click="handleDelete(idx,'bSellMa')">删除</el-button>
       </div>
       <el-cascader :props="props" class="newSelect" :lazy="true" ref="cascaderRef" :options="options" :show-all-levels="false" v-model="ruleForm.maidiepingcang[idx]">
        <template #default="{ node, data }">
         <!-- 判断是否为第三级节点 -->
         <div v-if="isThirdLevel(node)">
          <selectConfig :data="data" @onValue="value => onValue(value, data, node)" />
         </div>
         <span v-else>{{ data.label }}</span>
        </template>
       </el-cascader>
      </div>
     </div>
    </el-collapse-item>

   </el-collapse>

   <div class="policy">
    <el-input v-model="ruleForm.strategy_name" class="policyName" placeholder="请输入策略名称"></el-input>
    <div class="transaction_price_box">
     <p class="setting_tit">交易执行价格设置</p>
     <div class="row flex">
      <div class="col flex">
       买涨
       <el-input
        v-model="ruleForm.price_set.buy_up"
        :maxlength="5"
        class="marR1"
       >
       </el-input
       >%
      </div>
      <div class="col flex">
       买涨平仓
       <el-input
        v-model="ruleForm.price_set.buy_up_close"
        :maxlength="4"
        class="marR1"
       >
       </el-input
       >%
      </div>
      <div class="col flex">
       买跌
       <el-input v-model="ruleForm.price_set.buy_down" :maxlength="4" class="marR1"></el-input>%
      </div>
      <div class="col flex">
       买跌平仓
       <el-input v-model="ruleForm.price_set.buy_up_close" :maxlength="4" class="marR1"></el-input>%
      </div>

      <div class="col flex">
       交易执行手数：
       <el-input v-model="ruleForm.price_set.fix_size" :maxlength="5" class="marR1"></el-input>手
      </div>
     </div>

     <div class="btns flex">
      <el-button type="primary" @click="handleAddPrice(1)">调试</el-button>
      <el-button type="primary" @click="handleAddPrice(0)">保存</el-button>
     </div>
    </div>
   </div>
  </div>
 </div>
</template>

<style scoped lang="scss">
::v-deep {
 .el-cascader {
  height: 36px;
  overflow: hidden;
 }
}
.el-collapse {
 border: none;
 ::v-deep {
  .el-collapse-item {
   .el-collapse-item__header {
    background-color: transparent;
    border-bottom-color: $card_border_color;
   }
   .el-collapse-item__arrow {
    color: #fff;
    margin: 0;
    font: {
     size: 20px;
    }
   }
  }

  .el-collapse-item__wrap{
   background-color: transparent;
   border-bottom-color: $card_border_color;
  }
 }
}

.collapse {
 width: 100%;
 justify-content: space-between;

 ::v-deep {
  h6 {
   @include Font((color: $white, size: 14px));
  }
  svg {
   width: 20px;
   color: #fff;
  }
 }
}

.box {
 flex-wrap: wrap;

 .price {
  margin-top: 15px;
  flex-direction: column;
  width: calc(50% - 15px);

  &:nth-of-type(odd) {
   margin-right: 30px;
  }

  &_header {
   margin-bottom: 10px;
   justify-content: space-between;
   align-items: center;


   p {
    @include Font((color: $colorA, size: 14px));
   }
  }
 }
}

.policy {
 margin-top: 20px;

 .setting_tit {
  margin-bottom: 10px;
  @include Font((color: $colorA, size: 14px));
 }

 .row {
  margin-bottom: 20px;
  flex-wrap: wrap;
 }

 .col {
  margin-bottom: 15px;
  align-items: center;
  width: calc(50% - 5px);
  @include Font((color: $colorA, size: 12px));

  &:nth-of-type(odd) {
   margin-right: 10px;
  }
  .el-input {
   margin: 0 5px;
   width: 50px;
  }
 }
 >.el-input {
  margin-bottom: 10px;
  width: 100px;
 }

 .el-input {
  ::v-deep {
   .el-input__wrapper {
    background-color: transparent;
    box-shadow: 0 0 0 1px $card_border_color inset;
    .el-input__inner {
     color: $white;
    }
   }
  }
 }
}

.btns {
 justify-content: end;
}
</style>